﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SqlSugar;

namespace GeneratedEntity
{
    /// <summary>
    /// author: Yang.Gu
    /// create date: 2020年7月30日00:38:33
    /// tel：13482198105
    /// </summary>
    public partial class GeneratedEntityForm : Form
    {
        public GeneratedEntityForm()
        {
            InitializeComponent();
            //lB_tables.Items.Add("xxsh_test_master");
          


        }
        public string dbconnection = "";
        private void b_GeneratedEntity_Click(object sender, EventArgs e)
        {
            if (!firstPartFlag)
            {
                MessageBox.Show("请先执行第一部分逻辑（设定数据库连接字符串，并且选择想要生成的表），谢谢");
                return;
            }
            if (tB_generatepath.Text.ToString().Trim().Length<1)
            {
                MessageBox.Show("未找到生成路径");
                return;
            }
            string path = tB_generatepath.Text.ToString().Trim();
            if (path.Length>2 && path.Substring(path.Length-2,2) =="\\\\" )
            {

            }
            else
            {
                path = path + "\\\\";
            }
            if (tB_namespace.Text.ToString().Trim().Length < 1)
            {
                MessageBox.Show("命名空间为空");
                return;
            }

           
            string namespace1 = tB_namespace.Text.ToString().Trim();


            

            ConnectionConfig _conn = new ConnectionConfig();

            switch (cB_dbtype.SelectedItem.ToString().ToLower())
            {
                case "oracle":
                    _conn.DbType = SqlSugar.DbType.Oracle;         //必填, 数据库类型
                    //dbconnection = $"Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = {ip})(PORT = {port})))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = {SERVICE_NAME})));User Id={username};Password={password};Pooling=true;MAX Pool Size=20;Min Pool Size=5;Connection Lifetime=20;Connect Timeout=20;";

                    break;
                case "mysql":
                    _conn.DbType = SqlSugar.DbType.MySql;         //必填, 数据库类型
                    //dbconnection = $"Server={ip};Port={port};Database={SERVICE_NAME};Uid={username};Pwd={password};default command timeout=20;Connection Timeout=5;";
                    break;
                case "sqlserver":
                    _conn.DbType = SqlSugar.DbType.SqlServer;         //必填, 数据库类型
                    //dbconnection = $"Server={ip};Database={SERVICE_NAME};User Id={username};Password={password};";
                    break;
                case "sqlite":
                    _conn.DbType = SqlSugar.DbType.Sqlite;         //必填, 数据库类型
                    //dbconnection = $"Data Source={SERVICE_NAME};Version=3;Password={password};";
                    break;
                case "postgresql":
                    _conn.DbType = SqlSugar.DbType.PostgreSQL;         //必填, 数据库类型
                    //dbconnection = $"User ID={username};Password={password};Host={ip};Port={port};Database={SERVICE_NAME};Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;";
                    break;

                default:
                    break;
            }
            _conn.ConnectionString = dbconnection;//必填, 数据库连接字符串
            _conn.IsAutoCloseConnection = true;    //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
            _conn.InitKeyType = InitKeyType.SystemTable;    //默认SystemTable, 字段信息读取, 如：该属性是不是主键，是不是标识列等等信息
            SqlSugarClient db = new SqlSugarClient(_conn);

            string tablename = lB_tables.SelectedItem.ToString();

            db.DbFirst.Where(tablename).CreateClassFile(path, namespace1);

            if (File.Exists(path+tablename+".cs"))
            {
                System.Diagnostics.Process.Start("Explorer", "/select," + path  + tablename + ".cs");
            }
            else if (File.Exists(path  + tablename + ".CS"))
            {
                System.Diagnostics.Process.Start("Explorer", "/select," + path  + tablename + ".CS");
            }
            else
            {
                MessageBox.Show($"未在该文件夹:{path}  \r\n找到生成的 {tablename} .cs文件，可能是未找到该表或者表名匹配不成功");
            }
            
        }
        public bool firstPartFlag = false;
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                lB_tables.Items.Clear();

                //dbconnection = $"Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = {ip})(PORT = {port})))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = {SERVICE_NAME})));User Id={username};Password={password};Pooling=true;MAX Pool Size=20;Min Pool Size=5;Connection Lifetime=20;Connect Timeout=20;";
                if (tB_connection.Text.Length<1)
                {
                    MessageBox.Show("连接字符串为空，请检查连接字符串");
                    return;
                }
                if (cB_dbtype.SelectedItem.ToString().Length<1)
                {
                    MessageBox.Show("请选择数据库类型");
                    return;
                }
                ConnectionConfig _conn = new ConnectionConfig();

                switch (cB_dbtype.SelectedItem.ToString().ToLower())
                {
                    case "oracle":
                        _conn.DbType = SqlSugar.DbType.Oracle;         //必填, 数据库类型
                        //dbconnection = $"Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = {ip})(PORT = {port})))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = {SERVICE_NAME})));User Id={username};Password={password};Pooling=true;MAX Pool Size=20;Min Pool Size=5;Connection Lifetime=20;Connect Timeout=20;";

                        break;
                    case "mysql":
                        _conn.DbType = SqlSugar.DbType.MySql;         //必填, 数据库类型
                        //dbconnection = $"Server={ip};Port={port};Database={SERVICE_NAME};Uid={username};Pwd={password};default command timeout=20;Connection Timeout=5;";
                        break;
                    case "sqlserver":
                        _conn.DbType = SqlSugar.DbType.SqlServer;         //必填, 数据库类型
                        //dbconnection = $"Server={ip};Database={SERVICE_NAME};User Id={username};Password={password};";
                        break;
                    case "sqlite":
                        _conn.DbType = SqlSugar.DbType.Sqlite;         //必填, 数据库类型
                        //dbconnection = $"Data Source={SERVICE_NAME};Version=3;Password={password};";
                        break;
                    case "postgresql":
                        _conn.DbType = SqlSugar.DbType.PostgreSQL;         //必填, 数据库类型
                        //dbconnection = $"User ID={username};Password={password};Host={ip};Port={port};Database={SERVICE_NAME};Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;";
                        break;

                    default:
                        break;
                }
                dbconnection = tB_connection.Text.ToString();
                _conn.ConnectionString = dbconnection;//必填, 数据库连接字符串
                _conn.IsAutoCloseConnection = true;    //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
                _conn.InitKeyType = InitKeyType.SystemTable;    //默认SystemTable, 字段信息读取, 如：该属性是不是主键，是不是标识列等等信息


                SqlSugarClient db = new SqlSugarClient(_conn);
                switch (cB_dbtype.SelectedItem.ToString().ToLower())
                {
                    case "oracle":
                        //_conn.DbType = SqlSugar.DbType.Oracle;         //必填, 数据库类型
                        //dbconnection = $"Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = {ip})(PORT = {port})))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = {SERVICE_NAME})));User Id={username};Password={password};Pooling=true;MAX Pool Size=20;Min Pool Size=5;Connection Lifetime=20;Connect Timeout=20;";
                        var oraclelist = db.SqlQueryable<dynamic>("SELECT * FROM USER_TABLES").ToList();
                        lB_tables.Items.Clear();
                        List<string> _oracletables = new List<string>();
                        foreach (var item in oraclelist)
                        {
                            _oracletables.Add(item.TABLE_NAME);
                            //lB_tables.Items.Add(item.TABLE_NAME);
                        }
                        _oracletables.Sort();
                        foreach (var item in _oracletables)
                        {
                            lB_tables.Items.Add(item);
                        }
                        break;
                    case "mysql":
                        //_conn.DbType = SqlSugar.DbType.MySql;         //必填, 数据库类型
                        //dbconnection = $"Server={ip};Port={port};Database={SERVICE_NAME};Uid={username};Pwd={password};default command timeout=20;Connection Timeout=5;";
                        break;
                    case "sqlserver":
                        var sqlserverlist = db.SqlQueryable<dynamic>("select * from sys.tables").ToList();
                        lB_tables.Items.Clear();
                        List<string> _sqlservertables = new List<string>();
                        foreach (var item in sqlserverlist)
                        {
                            _sqlservertables.Add(item.name);
                        }
                        _sqlservertables.Sort();
                        //lB_tables.Items.Add("");// = _tables;

                        foreach (var item in _sqlservertables)
                        {
                            lB_tables.Items.Add(item);
                        }
                        //_conn.DbType = SqlSugar.DbType.SqlServer;         //必填, 数据库类型
                        //dbconnection = $"Server={ip};Database={SERVICE_NAME};User Id={username};Password={password};";
                        break;
                    case "sqlite":
                        //_conn.DbType = SqlSugar.DbType.Sqlite;         //必填, 数据库类型
                        //dbconnection = $"Data Source={SERVICE_NAME};Version=3;Password={password};";
                        break;
                    case "postgresql":
                        //_conn.DbType = SqlSugar.DbType.PostgreSQL;         //必填, 数据库类型
                        //dbconnection = $"User ID={username};Password={password};Host={ip};Port={port};Database={SERVICE_NAME};Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;";
                        break;

                    default:
                        break;
                }

                firstPartFlag = true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                MessageBox.Show("程序出现异常:"+ex.Message);
                //throw;
            }
        }

        private void tB_generatepath_Click(object sender, EventArgs e)
        {
            string path = string.Empty;
            System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                path = fbd.SelectedPath;
            }
            tB_generatepath.Text = path;
        }

    
        private void lL_path_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                FolderBrowserDialog dialog = new FolderBrowserDialog();
                dialog.Description = "请选择文件路径";

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string savePath = dialog.SelectedPath;
                    tB_generatepath.Text = savePath;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("出现异常，原因是："+ex.Message);
                tB_generatepath.Text = "";
                //throw;
            }
        }
    }
}
